import axios from 'axios';
import Cookies from "js-cookie";
import errorCode from '#/utils/errorCode'
import router from "#/router";
import {ElMessage} from 'element-plus'

axios.create({
    baseURL: '/api', // 所有的请求地址前缀部分
    timeout: 60000, // 请求超时时间毫秒
    withCredentials: true, // 异步请求携带cookie
    headers: {
        // 设置后端需要的传参类型
        'Content-Type': 'application/json',
        'token': Cookies.get("token"),
        'X-Requested-With': 'XMLHttpRequest',
    },
})
// const {CancelToken} = axios;
// const source = CancelToken.source();

axios.interceptors.request.use(
    (config) => {
        if (Cookies.get("token") || config.url == '/captchaImage' || config.url == '/login') {
            if (!config.url.includes('http')) {
                const urlList = window.WORKBENCH.URL;
                if (!config.module || !Object.keys(urlList).includes(config.module)) {
                    config.module = 'auth';
                }
                // const host = urlList[config.module];
                config.url = `${config.module}${config.url}`;
                //config.baseURL = urlList[config.module];

            }
            //config.cancelToken = Cookies.get("token"); // 全局添加cancelToken
            config.headers['X-Requested-With'] = 'XMLHttpRequest';
            if (config.url !== '/captchaImage' && config.url !== '/login') {
                config.headers['token'] = Cookies.get("token");
                config.headers['access_token'] = Cookies.get("token");
                config.headers.Authorization = `Bearer ${Cookies.get("token")}`;
            }
            return config;
        } else {
            router.push({path: '/login'});
        }
    },
    (error) => {
        debugger;
        return Promise.reject(error);
    }
)

// 响应拦截器
axios.interceptors.response.use(res => {
// 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        return res.data
    }
    if (code === 401) {
        router.push({path: '/login'});
        ElMessage.error('无效的会话，或者会话已过期，请重新登录。');
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 200) {
        return res.data
    } else {
        ElMessage.error(msg)
    }
});

export default axios;
